$(function(){
	var uid = $("#uid").val();
	var gid = $("#gid").val();
	var price = $("#price").val();
	var discount = $("#discount").val();
	var newGoodPrice = (price*discount).toFixed(2);
	var gcid = 0;
	var gsid = 0;
	var nums = 0;
	var jsonGoodNum = {};
	jsonGoodNum['gid'] = gid;
	
	//初始化加载商品数量
	loadGoodNum(jsonGoodNum);
	
//	alert("uuid"+uid+"数据")
	
	//监听颜色下拉框
	$("select#color").change(function(){
		gcid = $(this).val().split(",")[0];
		jsonGoodNum['gcid'] = gcid;
		loadGoodNum(jsonGoodNum);
	});
	
	//监听尺寸选择
	$("select#size").change(function(){
		gsid = $(this).val().split(",")[0];
		jsonGoodNum['gsid'] = gsid;
		loadGoodNum(jsonGoodNum);
	});
	
	//加载商品数量
	function loadGoodNum(){
		$.ajax({
			type:"post",
			url:"goodnum/findSum",
			async:false,
			data:jsonGoodNum,
			success:function(data){
				if(data===''){
					data = 0;
				}
				$("#goodNums").text(data);
				nums = data;
				$('#newGoodPrice').text(newGoodPrice);
				$('#carPrice').text(newGoodPrice);
			},error:function(){
				swal("服务器异常!","","warning",{buttons: {}});
			}
		}); 
	}
	
	//点击增加商品
	$(".plus").click(function(){
		var checknums = $("#numsInp").val();
		if(checknums<nums){
			checknums++;
			$("#numsInp").val(checknums);
			$('#carPrice').text((newGoodPrice*checknums).toFixed(2));
		}
	});
	
	//点击减少商品
	$(".minus").click(function(){
		var checknums = $("#numsInp").val();
		if(checknums>0){
			checknums--;
			$("#numsInp").val(checknums);
			$('#carPrice').text((newGoodPrice*checknums).toFixed(2));
		}
	});
	
	//填写数量
	$("#numsInp").blur(function(){
		$('#carPrice').text((newGoodPrice*$("#numsInp").val()).toFixed(2));
	});
	
	//监听提交
	$("#add-to-cart").click(function(){
	
		if(uid!=''){
			if(gcid!=0){
				if(gsid!=0){
					if(nums!=0){
						if($("#numsInp").val()<=nums){
							var reg = /^[1-9]\d*$/;			//正整数的正则表达式
							if($("#numsInp").val()!=0&&$("#numsInp").val()!=''&&reg.test($("#numsInp").val())){
								jsonGoodNum['user.uid'] = uid;
								jsonGoodNum['good.gid'] = gid;
								jsonGoodNum['goodColor.gcid'] = $("#color").val().split(",")[0];
								jsonGoodNum['goodSize.gsid'] = $("#size").val().split(",")[0];
								$.ajax({
									url:'car/loadObjectByPramas',
									type:"post",
									data:jsonGoodNum,
									success:function(data){
										if(data==null||data==''){
											jsonGoodNum['makeCarDate'] = new Date();
											jsonGoodNum['cnum'] = $("#numsInp").val();
											jsonGoodNum['cprice'] = $('#carPrice').text();
											jsonGoodNum['cstate'] = 1;
											//获取结束时间
											$.ajax({
												url:'car/findMonth',
												type:"post",
												data:{endCarDate: new Date()},
												success:function(res){
													jsonGoodNum['endCarDate'] = formatDateTime(res);
													//执行添加到购物车
													//console.log(jsonGoodNum);
													console.log("时间码"+res.endCarDate)
													console.log(jsonGoodNum)
													saveGoodCar(jsonGoodNum);
													
												},
												error:function(){
													swal("对不起,服务器异常!"," ","warning",{buttons: {}});
												} 
											});
										}else{
												//获取结束时间
												$.ajax({
													url:'car/findMonth',
													type:"post",
													data:{endCarDate: new Date()},
													success:function(res){
														jsonGoodNum['endCarDate'] = formatDateTime(res.endCarDate);
														//执行添加到购物车
  													 
														//console.log(jsonGoodNum);
														jsonGoodNum['cnum'] = parseInt(data.cnum)+parseInt($("#numsInp").val());
														jsonGoodNum['cprice'] = ((parseInt(data.cnum)+parseInt($("#numsInp").val()))*$("#discount").val()*$("#price").val()).toFixed(2);
														jsonGoodNum['makeCarDate'] = new Date();
														jsonGoodNum['cstate'] = 1;
														console.log(jsonGoodNum);
														$.ajax({
															url:'car/updT',
															type:"post",
															data:jsonGoodNum,
															success:function(res){
																if(res=='success'){
																	swal("添加购物车成功!"," ","success",{buttons: {}});
																	setTimeout('window.location = "good/goodDetails?gid='+gid+'"', 1000);
																}else{
																	swal("对不起,添加购物车失败!"," ","warning",{buttons: {}});
																}
															},
															error:function(){
																swal("对不起,服务器异常!"," ","warning",{buttons: {}});
															} 
														});
														jsonGoodNum['gid'] = gid;
														jsonGoodNum['gcid'] = $("#color").val().split(",")[0];
														jsonGoodNum['gsid'] = $("#size").val().split(",")[0];
														jsonGoodNum['gnum'] = $("#goodNums").text()-$("#numsInp").val();
														$.ajax({
															url:'goodnum/updT',
															type:"post",
															data:jsonGoodNum,
															success:function(data){
																if(data=='success'){
																	$("#goodNums").text(($("#goodNums").text()-$("#numsInp").val()));
																}else{
																	swal("对不起,修改库存失败!"," ","warning",{buttons: {}});
																}
															},
															error:function(){
																swal("对不起,服务器异常!"," ","warning",{buttons: {}});
															} 
														});
														
													},
													error:function(){
														swal("对不起,服务器异常!"," ","warning",{buttons: {}});
													} 
												});
										}
									},
									error:function(){
										swal("对不起,服务器异常!"," ","warning",{buttons: {}});
									} 
								});
							}else{
								swal("商品数量输入有误!"," ","warning",{buttons: {}});
							}
						}else{
							swal("商品数量不能大于库存量!"," ","warning",{buttons: {}});
						}
					}else{
						swal("对不起,该商品暂时没有库存!"," ","warning",{buttons: {}});
					}
				}else{
					swal("您还未选择尺寸!"," ","warning",{buttons: {}});
				}
			}else{
				swal("您还未选择颜色!"," ","warning",{buttons: {}});
			}
		}else{
			swal("您未登陆,请先登陆!"," ","warning",{buttons: {}});
		}
	});
	
	//将时间戳转换为yyyy-MM-dd HH:mm:ss
	function formatDateTime(inputTime) {  
		console.log("时间源码："+inputTime);
	    var date = new Date(inputTime);
	    var y = date.getFullYear();
	    var m = date.getMonth() + 1;
	    m = m < 10 ? ('0' + m) : m;
	    var d = date.getDate();
	    d = d < 10 ? ('0' + d) : d;
	    var h = date.getHours();
	    h = h < 10 ? ('0' + h) : h;
	    var minute = date.getMinutes();
	    var second = date.getSeconds();
	    minute = minute < 10 ? ('0' + minute) : minute;  
	    second = second < 10 ? ('0' + second) : second; 
	    return y + '/' + m + '/' + d+' '+h+':'+minute+':'+second;
	};
	
	//商品添加到购物车
	function saveGoodCar(jsonGoodNum){
		$.ajax({
			url:'car/saveT',
			type:"post",
			data:jsonGoodNum,
			success:function(data){
				if(data=='success'){
					swal("恭喜你,加入购物车成功!"," ","success",{buttons: {}});
					var carHtml='';
					carHtml += '<li style="margin-bottom: 18px;">';
		            carHtml += '<a href="goodowGoodInfo?gid='+gid+'">';
		            carHtml += '<p style="margin-bottom: 5px;">'+$("#gname").val()+'</p>';
		            carHtml += '<img style="width: 60px;height: 60px;" alt="'+$("#gname").val()+'" src="/zzbinGood/g'+gid+'/'+$("#gpicpath").val()+'">';
		            carHtml += '</a><br/>';
		            carHtml += '<span>规格：'+$("#color").val().split(",")[1]+'&nbsp;/'+$("#size").val().split(",")[1]+'</span><br/><br/>';
		            carHtml += '<span class="quantity">'+$("#numsInp").val()+' × <span style="color:red;">'+(price*discount).toFixed(2)+'</span>';
		            carHtml += ' = <span style="color:red;">'+$('#carPrice').text()+'</span></span>'
		            $('.cart_list').prepend(carHtml);
					var jsonGoodNum = {};
					jsonGoodNum['gid'] = gid;
					jsonGoodNum['gcid'] = $("#color").val().split(",")[0];
					jsonGoodNum['gsid'] = $("#size").val().split(",")[0];
					jsonGoodNum['gnum'] = $("#goodNums").text()-$("#numsInp").val();
					$.ajax({
						url:'goodnum/updT',
						type:"post",
						data:jsonGoodNum,
						success:function(data){
							if(data=='success'){
								$("#goodNums").text(($("#goodNums").text()-$("#numsInp").val()));
								$("#counts").text(parseInt($("#counts").text())+1);
								$(".leftCarSpan").text((parseFloat($(".leftCarSpan").text())+parseFloat($("#carPrice").text())).toFixed(2));
							}else{
								swal("对不起,修改库存失败!"," ","warning",{buttons: {}});
							}
						},
						error:function(){
							swal("对不起,服务器异常!"," ","warning",{buttons: {}});
						} 
					});
				}else{
					swal("对不起,加入购物车失败!"," ","warning",{buttons: {}});
				}
			},
			error:function(){
				swal("对不起,服务器异常!"," ","warning",{buttons: {}});
			} 
		});
	}
	
});

layui.use(['element', 'layer','flow','rate','form'], function(){
    var element = layui.element,
    layer = layui.layer,
    flow = layui.flow,
    rate = layui.rate,
    form = layui.form,
    $ = layui.$;
    

	//每一页的数据条数
	var limit = 2;
	var laef = 0;

	var limitGcollo = 2;
	var laefGcollo = 0;
	
	loadFlow();
	loadGcollocationFlow();
	
	//layui流加载
	function loadFlow(){
		flow.load({
			elem: '#goodEvaluateDiv'	//流加载容器
			,isAuto: false
			,done: function(page,next){	//执行下一页的回调
				//模拟数据插入
				setTimeout(function(){
					var lis = [];
					//加载订单
					loadGoodEvaluate(page);
					next(lis.join(''),page < laef);
				},500);
			}
		});
	}
	
	//加载评论数据
	function loadGoodEvaluate(page){
		var jsonGoodEvaluate = {};
		jsonGoodEvaluate['good.gid'] = $("#gid").val();
		jsonGoodEvaluate['page'] = page;
		jsonGoodEvaluate['limit'] = limit;
		$.ajax({
			url: 'goodEvaluate/listByPramas',
			type: 'post',
			data:jsonGoodEvaluate,
			async: false,
			success:function(res){
				if(res.code==0){
					var htmlContent = '';
					$.each(res.data,function(i,item){
						htmlContent += '<li class="comment"><div class="comment_container">';
						htmlContent += '<img style="margin-left: 15px;margin-bottom: 15px;width: 50px;height: 50px;" src="/zzbinUser/'+item.user.avater+'" class="avatar">';
						htmlContent += '<div class="comment-text"><div class="start-rating">';
						htmlContent += '<span class="glyphicon glyphicon-star"></span>';
						htmlContent += '<span class="glyphicon glyphicon-star"></span>';
						htmlContent += '<span class="glyphicon glyphicon-star"></span>';
						htmlContent += '<span class="glyphicon glyphicon-star"></span>';
						htmlContent += '<span class="glyphicon glyphicon-star"></span>';
						htmlContent += '<span class="glyphicon glyphicon-star"></span></div>';
						htmlContent += '<h5>'+item.user.uname+'<span style="margin-left: 15px;">'+item.geDate+'</span><span style="color: #AD5A5A;margin-left: 15px;">颜色分类：'+item.goodColor.gcname+'--尺码：'+item.goodSize.gsname+'</span></h5><p>'+item.geContent+'</p>';
						htmlContent += '</div></div></li>';
	      			});
	      			$(".layui-collapse").append(htmlContent);	//追加页面元素
	      			element.init();
				}else{
					layer.msg("评论加载失败！",{"icon":5,"time":2000});
				}
				var counts = res.count;
				if(counts%limit==0){
					laef = counts/limit;
				}else{
					laef = parseInt(counts/limit)+1;
				}
			},
			error:function(){
				layer.msg("服务器异常！",{"icon":3,"time":2000});
			}
		});
	}
	
	//layui流加载
	function loadGcollocationFlow(){
		flow.load({
			elem: '#gcollocationDiv'	//流加载容器
			,isAuto: true
			,done: function(page,next){	//执行下一页的回调
				//模拟数据插入
				setTimeout(function(){
					var lis = [];
					//加载订单
					loadGcollocation(page);
					next(lis.join(''),page < laefGcollo);
				},500);
			}
		});
	}
	
	//加载商品详情图
	function loadGcollocation(page){
		var jsonGcollocation = {};
		jsonGcollocation['good.gid'] = $("#gid").val();
		jsonGcollocation['page'] = page;
		jsonGcollocation['limit'] = limitGcollo;
		$.ajax({
			url: 'gcollocation/listByPramas',
			type: 'post',
			data:jsonGcollocation,
			async: false,
			success:function(res){
				if(res.code==0){
					var htmlContent = '';
					$.each(res.data,function(i,item){
						htmlContent += '<li style="display:inline-block;margin-left: 40px;margin-top: 20px;"><div class="layui-anim layui-anim-rotate"><img src="/zzbinGood/p'+$("#gid").val()+'/'+item.gcollo+'" style="width: 500px;"/></div></li>';
	      			});
	      			$("#gcollocation").append(htmlContent);	//追加页面元素
	      			element.init();
				}else{
					layer.msg("图片加载失败！",{"icon":5,"time":2000});
				}
				var counts = res.count;
				if(counts%limitGcollo==0){
					laefGcollo = counts/limitGcollo;
				}else{
					laefGcollo = parseInt(counts/limitGcollo)+1;
				}
			},
			error:function(){
				layer.msg("服务器异常！",{"icon":3,"time":2000});
			}
		});
	}
	
});